<?php

namespace app\admin\controller\api;

use app\admin\library\DistinguishAddress;
use app\admin\model\AuthGroupAccess;
use app\common\model;
use app\common\model\Grade;
use think\Db;

/**
 * 学校
 * @internal
 */
class School extends Api
{
    protected $noNeedLogin = [
        'resetAddress',
        'teacherIds',
        'studentIds',
        'teacherAndStudentIds',
        'teacherUpdatedAvatars',
        'studentUpdatedAvatars',
        'updatedAvatars',
        'teacher',
        'student',
        'deletedTeachers',
        'deletedStudents',
    ];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 学校列表
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $list = model\School::whereIn('id', $this->getSchoolIds())
            ->field('id,pid,name,province_id,city_id,district_id,address,logo,code,note')
            ->select();
        $this->success('', $list);
    }

    /**
     * 当前用户权限下的 school_ids
     *
     * @User ZhenZiHan
     * @Date 2020/3/16
     *
     */
    public function ids()
    {
        $this->success('', $this->getSchoolIds());
    }

    /**
     * 学校列表
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function lists()
    {
        $list = model\School::whereIn('id', $this->getSchoolIds())
            ->field('id,pid,name,province_id,city_id,district_id,address,logo,code,note')
            ->select();
        $this->success('', $list);
    }

    /**
     * 学校内的所有教室
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function classrooms()
    {
        $school_id = $this->request->request('school_id');

        $result = model\School::alias('school')
            ->join('__GARDEN__ garden', 'garden.school_id = school.id')
            ->join('__BUILDING__ building', 'building.garden_id = garden.id')
            ->join('__CLASSROOM__ classroom', 'classroom.building_id = building.id')
            ->field('classroom.id,classroom.number,classroom.name,classroom.type,classroom.floor,classroom.capacity,garden.name garden_name,building.name building_name,school.name school_name')
            ->where('school_id', $school_id)
            ->select();

        $this->success('', $result);
    }

    /**
     * 重置学校的地址
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function resetAddress()
    {
        set_time_limit(0);
        $schools = model\JSchool::field('id,merger_name')->where('d_id', null)->where('c_id', '>', 0)->select();
        $DistinguishAddress = new DistinguishAddress();
        $data = [];
        foreach ($schools as $key => $school) {
            $address = $DistinguishAddress->getAddressResult($school->merger_name);
            $data[] = [
                'id' => $school->id,
                'p_id' => isset($address['province']) ? $address['province']['id'] : 0,
                'c_id' => isset($address['city']) ? $address['city']['id'] : 0,
                'd_id' => isset($address['district']) ? $address['district']['id'] : 0
            ];
        }
        $school = new model\JSchool();
        $limit = 500;
        $count = ceil(count($data) / $limit);
        for ($i = 1; $i <= $count; $i++) {
            $offset = ($i - 1) * $limit;
            $update_data = array_slice($data, $offset, $limit);
            $school->saveAll($update_data);
        }
    }

    /**
     * 学科列表
     *
     * @param school_id int 学校id
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function subjects()
    {
        $school_id = $this->request->request('id', 0);

        $list = model\Subject::where('school_id', $school_id)->field('id,name')->select();

        $this->success('', $list);
    }

    /**
     * 年级列表
     *
     * @throws \think\exception\DbException
     */
    public function grades()
    {
        $list = model\Grade::all();
        $this->success('', $list);
    }

    /**
     * @ApiTitle    (班级列表)
     * @ApiAuthor   (Zhenzh)
     * @ApiDate     (2020/1/15)
     * @ApiSummary  (描述)
     * @ApiBody     (Body)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/school/classes)
     * @ApiParams   (name="id", type="int", required=true, description="学校 ID", sample="36")
     * @ApiParams   (name="grade_id", type="int", required=false, description="年级 ID", sample="1")
     * @ApiReturnParams   (name="code", type="integer", required=true, description="状态码 1正常 0错误", sample="1")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", description="扩展数据返回", sample="")
     * @ApiReturn ({
    "code": 1,
    "msg": "",
    "time": "1579071493",
    "data": [
    {
    "id": 1,
    "name": "一年级",
    "stage": 1,
    "key": 1,
    "classes": [
    {
    "id": 52,
    "name": "1班",
    "school_id": 36,
    "grade_id": 1,
    "classroom_id": 30,
    "headmaster": 42,
    "slogan": null,
    "logo": null,
    "school_id": 3,
    "created_at": 1573873470,
    "type": 1
    },
    {
    "id": 97,
    "name": "实验室",
    "school_id": 36,
    "grade_id": 1,
    "classroom_id": 35,
    "headmaster": 48,
    "slogan": "书上得来终觉浅,绝知此事要躬行",
    "logo": null,
    "school_id": 3,
    "created_at": 1574666014,
    "type": 1
    },
    {
    "id": 98,
    "name": "3班",
    "school_id": 36,
    "grade_id": 1,
    "classroom_id": 30,
    "headmaster": 42,
    "slogan": " 1234",
    "logo": "/uploads/20191126/8284af499ea84f5bb8517c815867e7c3.jpg",
    "school_id": 3,
    "created_at": 1574752789,
    "type": 1
    }
    ]
    }
    ]
    })
     */
    public function classes()
    {
        $id = $this->request->request('id', 0);
        $grade_id = $this->request->request('grade_id', 0);
        $keywords = $this->request->request('keywords', '');

        if (!$id) {
            $this->error('参数有误');
        }

        $list = Grade::with(['classes' => function ($query) use ($id, $keywords) {
            $query->where('school_id', $id);
            if ($keywords) {
                $query->whereLike('name', "%$keywords%");
            }
        }])
            ->where(function ($query) use ($grade_id) {
                if ($grade_id) {
                    $query->where('id', $grade_id);
                }
            })->select();

        if ($list) {
            foreach ($list as $key => $value) {
                foreach ($value['classes'] as $k => $class) {
                    if (!strstr($class['logo'], 'http') && strstr($class['logo'], '/uploads/')) {
                        $list[$key]['classes'][$k]['logo'] = config('app_url') . $class['logo'];
                    }
                }
            }
        }

        $this->success('', $list);
    }

    /**
     * 教师列表
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function teachers()
    {
        $school_id = $this->request->request('id', 0);

        $list = model\Teacher::alias('teacher')
            ->join('__USER__ user', 'user.id = teacher.user_id')
            ->field('teacher.id,user.nickname teacher_name,user.gender,user.avatar')
            ->where('teacher.school_id', $school_id)
            ->select();

        if ($list) {
            $list = collection($list)->toArray();

            foreach ($list as $key => $value) {
                if (!strstr($value['avatar'], 'http') && strstr($value['avatar'], '/uploads')) {
                    $list[$key]['avatar'] = config('app_url') . $value['avatar'];
                }
            }
        }



        $this->success('', $list);
    }

    /**
     * 统计学校内的 班级数、教师数、家长数、学生数
     *
     * @throws \think\Exception
     */
    public function statistics()
    {
        $school_id = $this->request->request('id', 0);

        $classes_count = model\Classes::where('school_id', $school_id)->count();
        $teacher_count = model\Teacher::where('school_id', $school_id)->count();
        $parents_count = model\Parents::where('school_id', $school_id)->count();
        $student_count = model\Student::where('school_id', $school_id)->count();

        $this->success('', compact('classes_count', 'teacher_count', 'parents_count', 'student_count'));
    }

    /**
     * 根据学校id获取园区列表
     *
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function gardens()
    {
        $id = $this->request->request('id');
        $result = model\Garden::where('school_id', $id)->field('id,number,name')->select();

        $this->success('', $result);
    }

    public function profile()
    {
        $ids = $this->request->request('ids/a');

        $list = model\School::whereIn('id', $ids)->column('*', 'id');

        $this->success('', $list);
    }

    public function info()
    {
        $id = $this->request->request('id');

        $data = model\School::where('id', $id)->find();

        $this->success('', $data);
    }

    public function detail()
    {
        $id = $this->request->request('id');

        $result = model\School::get($id);

        $this->success('', $result);
    }

    public function students()
    {
        $list = model\Student::where('school_id', $this->_user['school_id'])->field('id,school_id')->select();

        $this->success('', $list);
    }

    public function studentBeds()
    {
        $list = model\Student::alias('student')
            ->join('__SCHOOL__ school', 'school.id = student.school_id')
            ->where('student.school_id', $this->_user['school_id'])
            ->field('student.school_id id,school.name school_name,COUNT(student.gender = 1 OR NULL) boy_count,COUNT(student.gender = 0 OR NULL) girl_count')
            ->where('student.is_bed', 0)
            ->where('student.school_id', $this->_user['school_id'])
            ->group('student.school_id')
            ->select();

        $this->success('', $list);
    }

    public function studentCount()
    {
        $school_id = $this->request->request('school_id');
        $gender = $this->request->request('gender');
        $is_bed = $this->request->request('is_bed');

        $count = model\Student::where('school_id', $school_id)
            ->where('gender', $gender)
            ->where('is_bed', $is_bed)
            ->where('school_id', $this->_user['school_id'])
            ->count();
        $this->success('', $count);
    }

    public function studentNoBedList()
    {
        $school_id = $this->request->request('school_id');
        $gender = $this->request->request('gender');

        $list = model\Student::where('school_id', $school_id)
            ->where('gender', $gender)
            ->where('is_bed', 0)
            ->where('school_id', $this->_user['school_id'])
            ->field('id,name')
            ->select();
        $this->success('', $list);
    }

    public function teacherIds()
    {
        $id = $this->request->request('id', 0);
        $list = model\Teacher::where('school_id', $id)->field('id')->select();
        $this->success('', array_column($list, 'id'));
    }

    public function studentIds()
    {
        $id = $this->request->request('id', 0);
        $list = model\Student::where('school_id', $id)->field('id')->select();
        $this->success('', array_column($list, 'id'));
    }

    public function teacherAndStudentIds()
    {
        $id = $this->request->request('id', 0);

        $list = model\Teacher::where('school_id', $id)->field('id')->select();
        $data['teachers'] = array_column($list, 'id');

        $list = model\Student::where('school_id', $id)->field('id')->select();
        $data['students'] = array_column($list, 'id');

        $this->success('', $data);
    }

    public function teacherUpdatedAvatars()
    {
        $id = $this->request->request('id', 0);
        $time = $this->request->request('time', 0);

        if (!$id || !$time) {
            $this->error('参数有误');
        }
        $list = model\Teacher::where('school_id', $id)->where('avatar_updated_at', '>', $time)->field('id')->select();

        $this->success('', array_column($list, 'id'));
    }

    public function studentUpdatedAvatars()
    {
        $id = $this->request->request('id', 0);
        $time = $this->request->request('time', 0);

        if (!$id || !$time) {
            $this->error('参数有误');
        }
        $list = model\Student::where('school_id', $id)->where('avatar_updated_at', '>', $time)->field('id')->select();

        $this->success('', array_column($list, 'id'));
    }

    public function updatedAvatars()
    {
        $id = $this->request->request('id', 0);
        $time = $this->request->request('time', 0);

        if (!$id || !$time) {
            $this->error('参数有误');
        }

        $list = model\Teacher::where('school_id', $id)->where('avatar_updated_at', '>', $time)->field('id')->select();
        $data['teachers'] = array_column($list, 'id');
        $list = model\Student::where('school_id', $id)->where('avatar_updated_at', '>', $time)->field('id')->select();
        $data['students'] = array_column($list, 'id');

        $this->success('', $data);
    }

    public function teacher()
    {
        $school_id = $this->request->request('id', 0);
        $page = $this->request->request('page', 0);
        $list_rows = $this->request->request('list_rows', 10);
        if (!$school_id) {
            $this->error('参数错误');
        }

        if ($page) {
            $list = model\Teacher::alias('teacher')
                ->join('__USER__ user', 'user.id = teacher.user_id')
                ->field('teacher.id,user.nickname name,user.avatar,"" avatar_1')
                ->where('teacher.school_id', $school_id)
                ->where('user.avatar', '<>', 'NULL')
                ->where('user.avatar', '<>', '')
                ->paginate($list_rows);
        } else {
            $list = model\Teacher::alias('teacher')
                ->join('__USER__ user', 'user.id = teacher.user_id')
                ->field('teacher.id,user.nickname name,user.avatar,"" avatar_1')
                ->where('teacher.school_id', $school_id)
                ->where('user.avatar', '<>', 'NULL')
                ->where('user.avatar', '<>', '')
                ->select();
        }

        foreach ($list as $key => $student) {
            if (!strstr($student->avatar, 'http') && strstr($student->avatar, '/uploads')) {
                $student->avatar = config('app_url') . $student->avatar;
            }
        }

        $this->success('', $list);
    }

    public function student()
    {
        $school_id = $this->request->request('id', 0);
        $page = $this->request->request('page', 0);
        $list_rows = $this->request->request('list_rows', 10);
        if (!$school_id) {
            $this->error('参数错误');
        }

        if ($page) {
            $list = \app\common\model\Student::alias('student')
                ->where('student.school_id', $school_id)
                ->where('student.avatar', '<>', 'NULL')
                ->where('student.avatar', '<>', '')
                ->field('student.id,student.name,student.avatar,"" avatar_1')
                ->paginate($list_rows);

        } else {
            $list = \app\common\model\Student::alias('student')
                ->where('student.school_id', $school_id)
                ->where('student.avatar', '<>', 'NULL')
                ->where('student.avatar', '<>', '')
                ->field('student.id,student.name,student.avatar,"" avatar_1')
                ->select();
        }

        foreach ($list as $key => $value) {
            if (!strstr($value->avatar, 'http') && strstr($value->avatar, '/uploads')) {
                $value->avatar = config('app_url') . $value->avatar;
            }
        }

        $this->success('', $list);
    }

    public function deletedTeachers()
    {
        $id = $this->request->request('id', 0);
        $time = $this->request->request('time', 0);

        if (!$id || !$time) {
            $this->error('参数有误');
        }
        $list = model\Teacher::withTrashed()
            ->where('school_id', $id)
            ->where('deleted_at', '>', $time)
            ->field('id')
            ->select();

        $this->success('', array_column($list, 'id'));
    }

    public function deletedStudents()
    {
        $id = $this->request->request('id', 0);
        $time = $this->request->request('time', 0);

        if (!$id || !$time) {
            $this->error('参数有误');
        }
        $list = model\Student::withTrashed()
            ->where('school_id', $id)
            ->where('deleted_at', '>', $time)
            ->field('id')
            ->select();

        $this->success('', array_column($list, 'id'));
    }

}